package spring.in.action.chapter_03.conditional;

import java.util.List;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

class ProfileCondition implements Condition
{

    @Override
    public boolean matches(ConditionContext pContext, AnnotatedTypeMetadata pMetadata)
    {

        Environment lEnvironment = pContext.getEnvironment();
        if (lEnvironment == null)
        {
            return true;
        }
        MultiValueMap<String, Object> attrs = pMetadata
                .getAllAnnotationAttributes(Profile.class.getName());
        if (attrs == null)
        {
            return true;
        }
        List<Object> lValues = attrs.get("value");
        if (lEnvironment.acceptsProfiles((String[]) lValues.toArray()))
        {
            return true;
        }
        return false;
    }

}
